package com.zzedu.framework.config;

import com.baomidou.mybatisplus.core.handlers.MetaObjectHandler;
import com.zzedu.common.utils.SecurityUtils;
import org.apache.ibatis.reflection.MetaObject;
import org.springframework.stereotype.Component;

import java.time.LocalDateTime;

@Component
public class MyMetaObjectHandler implements MetaObjectHandler {
    @Override
    public void insertFill(MetaObject metaObject) {
        if (metaObject.hasGetter("deleted")) {
            this.strictInsertFill(metaObject, "deleted", Integer.class, 0);
        }

        if (metaObject.hasGetter("gmtCreate")) {
            this.strictInsertFill(metaObject, "gmtCreate", LocalDateTime.class, LocalDateTime.now());
        }

        if (metaObject.hasGetter("createBy")) {
            try {
                if (null != SecurityUtils.getSysUser() && null != SecurityUtils.getUserId()) {
                    this.strictInsertFill(metaObject, "createBy", Long.class, SecurityUtils.getUserId());
                }

            } catch (Exception e) {

            }
        }

    }

    @Override
    public void updateFill(MetaObject metaObject) {
        if (metaObject.hasGetter("gmtModify")) {
            this.strictUpdateFill(metaObject, "gmtModify", LocalDateTime.class, LocalDateTime.now());
        }
        if (metaObject.hasGetter("updateBy")) {
            try {
                if (null != SecurityUtils.getSysUser() && null != SecurityUtils.getSysUser()) {
                    this.strictUpdateFill(metaObject, "updateBy", Long.class, SecurityUtils.getUserId());
                }
            } catch (Exception e) {

            }
        }
    }
}
